package com.yanfan.energy.util;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";


    public static String SS_MM_HH_DD_HH_YY = "ssmmHHddMMyy";

    public static String YY_MM_DD_HH_MM_SS = "yy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTimeYY(Date date) {
        return DateFormatUtils.format(date, YY_MM_DD_HH_MM_SS);
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    public static long getTimestamp() {
        return System.currentTimeMillis();
    }

    public static long getTimestampSeconds() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 给定一个日期，返回今天是周几
     *
     * @param dt
     * @return 当前日期是周几
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    /**
     * 日期转字符串
     *
     * @param date
     * @return
     */
    public static String DateToStringYmd(Date date) {
        return DateFormatUtils.format(date, YYYY_MM_DD);
    }

    /**
     * 获取date的下一个月1号日期
     *
     * @param date yyyy-MM-dd
     * @return date的下一个月1号日期
     * @throws ParseException
     */
    public static String nextMonthFirstDate(String date) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(format.parse(date));   //设置时间提供的日期
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MONTH, 1);
        Date time = calendar.getTime();
        return format.format(time);
    }

    /**
     * 获取之前年份 月份的数据
     *
     * @param yearNum
     * @param monthNum
     * @return
     */
    public static Date getPreYearPreMon(int yearNum, int monthNum) {
        Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
        ca.setTime(new Date());   //设置时间为当前时间
        ca.add(Calendar.YEAR, -yearNum); //年份    -yearNum
        ca.add(Calendar.MONTH, -monthNum); // 月份 -monthNum
        return ca.getTime();
    }

    /**
     * 获取前几个月份
     *
     * @param monthNum
     * @return
     */
    public static Date getPreMon(int monthNum) {
        Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
        ca.setTime(new Date());   //设置时间为当前时间
        ca.add(Calendar.MONTH, -monthNum); // 月份 -monthNum
        return ca.getTime();
    }

    /**
     * 指定年月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month);
        //获取当月最小值
        int lastDay = cal.getMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中的月份，当月+1月-1天=当月最后一天
        cal.set(Calendar.DAY_OF_MONTH, lastDay - 1);
        return cal.getTime();
    }

    /**
     * @param end
     * @return
     */
    public static Date changeTheEnd(Date end) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(end);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }

    /**
     * 返回指定几天前的凌晨日期
     *
     * @param beforeNum
     * @return
     */
    public static Date getAppointDayTimestamp(int beforeNum) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, -beforeNum);
        return calendar.getTime();
    }

    /**
     * 返回指定几月前的1日 凌晨日期
     *
     * @param beforeNum
     * @return
     */
    public static Date getAppointMonthTimestamp(int beforeNum) {
        Calendar currCal = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, currCal.get(Calendar.YEAR));
        calendar.set(Calendar.MONTH, currCal.get(Calendar.MONTH) - beforeNum);
        return calendar.getTime();
    }


    /**
     * 返回指定几年前的一月一号凌晨
     *
     * @return
     */
    public static Date getAppointYearTimestamp(int beforeNum) {
        Calendar currCal = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, currCal.get(Calendar.YEAR) - beforeNum);
        return calendar.getTime();
    }

    /**
     * 指定年的最后一天
     *
     * @param year 指定年
     * @return
     */
    public static Date getLastDayOfYear(int year) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, 12);
        //设置日历中的月份，当月+1月-1天=当月最后一天
        cal.set(Calendar.DAY_OF_MONTH, 13);
        return cal.getTime();
    }

    /**
     * 计算当前月有多少天
     *
     * @param date
     * @return
     */

    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 返回本周 周一和周日的日期
     *
     * @return
     */
    public static Map<String, Date> getWeekDate() {
        Map<String, Date> map = new HashMap();
        Calendar cal = Calendar.getInstance();
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayWeek == 1) {
            dayWeek = 8;
        }
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        int week = cal.getFirstDayOfWeek() - dayWeek;
        cal.add(Calendar.DATE, week);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        map.put("beginDate", cal.getTime());
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DATE, 4 + cal.getFirstDayOfWeek());
        map.put("endDate", cal.getTime());
        return map;
    }

    /**
     * 指定月份的天数 , flag
     *
     * @param date
     * @param flag 为date的上下几月标识  正数往后推，往前推   0 为用户提供的日期月份天数  1 为 下一个月份的天数 ，反之 -1为前一个月的天数
     * @return
     */
    public static Integer numberOfDays(Date date, Integer flag) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + flag);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }


    /**
     * 返回昨天整点
     *
     * @return
     */
    public static Date getYesterdayTimestamp() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        return calendar.getTime();
    }

    /**
     * 返回这个月1号整点
     *
     * @return
     */
    public static Date getThisMonth() {
        Calendar currCal = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, currCal.get(Calendar.YEAR));
        calendar.set(Calendar.MONTH, currCal.get(Calendar.MONTH));
        return calendar.getTime();
    }


    /**
     * 返回今年1月1号整点
     *
     * @return
     */
    public static Date getThisYear() {
        Calendar currCal = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, currCal.get(Calendar.YEAR));
        return calendar.getTime();
    }

    /**
     * 返回明天 下个时间
     *
     * @return
     */
    public static Date nextTomorrow(Date date) {
        // 创建 Calendar 对象
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 将时间增加一天
        calendar.add(Calendar.DATE, 1);
        return calendar.getTime();
    }

    /**
     * 下周几的日期
     *
     * @return
     */
    public static Date nextWeak(Date date) {
        // 创建 Calendar 对象
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 将时间增加一天
        calendar.add(Calendar.DATE, 7);
        return calendar.getTime();
    }


    /**
     * 下个月的几号  比如给了一个时间为  2023-01-31 时:分:秒   返回日期    2023-03-31 时:分:秒
     *
     * @param date
     * @return
     */
    public static Date nextMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int day = calendar.get(Calendar.DATE); // 找到日期的 为多少号
        int month = calendar.get(Calendar.MONTH) + 1; // 找到日期的 为多少月
        // 判断：如果是有31天并且不是七月
        if (day == 31 && month != 7) {
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 2);
        } else {
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
        }
        return calendar.getTime();
    }

    /**
     * 指定月份的
     * * 根据年分 和月份  返回那个月第一天
     *
     * @param year  年分
     * @param month 月份
     * @return 指定年月份的第一天
     */
    public static Date getFirstMonthDay(int year, int month) {
        //获取当前月第一天：
        Calendar ca = Calendar.getInstance();
        ca.clear();
        ca.set(Calendar.YEAR, year);
        ca.set(Calendar.MONTH, month - 1);
        ca.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        ca.set(Calendar.HOUR, 0);
        ca.set(Calendar.MINUTE, 0);
        ca.set(Calendar.SECOND, 0);
        return ca.getTime();
    }


    public static Date getLastMonthDay(int year, int month) {
        //获取当前月最后一天
        Calendar ca = Calendar.getInstance();
        ca.clear();
        ca.set(Calendar.YEAR, year);
        ca.set(Calendar.MONTH, month - 1);
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        ca.set(Calendar.HOUR, 23);
        ca.set(Calendar.MINUTE, 59);
        ca.set(Calendar.SECOND, 59);

        return ca.getTime();
    }

    /**
     * 把日期转换为 字符串
     *
     * @param date
     * @return
     */
    public static String getYearMonthDateStr(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }


    /**
     * 返回今天整点
     *
     * @return
     */
    public static Date getTodayTimestamp() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 返回今天11:59:59
     *
     * @return
     */
    public static Date getTodayLastMinute() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }


    /**
     * 返回本月  1号和月底的日期
     *
     * @return
     */
    public static Map<String, Date> getMonthBeginEndDate() {
        Map<String, Date> map = new HashMap();
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        map.put("beginDate", calendar.getTime());
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        map.put("endDate", cal.getTime());
        return map;
    }

    /**
     * 获取当年的第一天
     */
    public static Date getCurrentFirstOfYear() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, currentYear);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取当年的最后一天
     */
    public static Date getCurrentLastOfYear() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, currentYear);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }


    /**
     * 判断是不是明天
     *
     * @param dateToCheck
     * @return
     */
    public static boolean isTomorrow(Date dateToCheck) {
        // 转成Calendar 对象
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateToCheck);
        // 创建 Calendar 对象
        Calendar tomorrow = Calendar.getInstance();
        tomorrow.setTime(new Date());
        tomorrow.add(Calendar.DAY_OF_YEAR, 1); // 第二天
        tomorrow.set(Calendar.HOUR, calendar.get(Calendar.HOUR));
        tomorrow.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE));
        tomorrow.set(Calendar.SECOND, calendar.get(Calendar.SECOND));
        tomorrow.set(Calendar.MILLISECOND, calendar.get(Calendar.MILLISECOND));
        tomorrow.set(Calendar.DST_OFFSET, calendar.get(Calendar.DST_OFFSET));
        // 获取 Calendar 对象表示的日期并将其转换为 Date 对象
        Date tomorrowDate = tomorrow.getTime();
        // 比较日期
        if (dateToCheck.compareTo(tomorrowDate) == 0) {
            return true;
        } else {
            return false;
        }
    }

    public static Double diff(Date startDate, Date endDate) {
        Integer datePoor = getDatePoor1(startDate, endDate);
        BigDecimal b = new BigDecimal((double) datePoor / 60);
        return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//第一个参数是保留小数的位数
    }

    public static Integer getDatePoor1(Date startDate, Date endDate) {
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startDate.getTime();
        Long mymint = diff / 1000 / 60;
        return mymint.intValue();
    }


    /**
     * 是否和cal 同一个月
     */
    public static String getSomeMonth() {
        Calendar cal = Calendar.getInstance();
        Date currentTime = cal.getTime();//当前时间的上个月时间
        return new SimpleDateFormat("yyyy-MM").format(currentTime);
    }

    /**
     * 返回上个月 年月信息
     */
    public static String getTheBeforeMonth() {
        Calendar cal = Calendar.getInstance();
        cal.add(cal.MONTH, -1);
        return new SimpleDateFormat("yyyy-MM").format(cal.getTime());
    }


    /**
     * 是否和cal 去年一个月
     */
    public static String getLastYearMonth() {
        Calendar cal = Calendar.getInstance();
        cal.add(cal.YEAR, -1);
        return new SimpleDateFormat("yyyy-MM").format(cal.getTime());
    }

    /**
     * 返回整点
     *
     * @return
     */
    public static Date theHours() {
        //获取一个 calendar日历对象, 该对象可以进行时间的计算
        Calendar date = Calendar.getInstance();
        date.set(Calendar.MINUTE, 00);
        return date.getTime();
    }


    public static String generateRandomHex(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        // 添加"D"作为开头
        sb.append("D");
        for (int i = 1; i < length; i++) {
            int randomInt = random.nextInt(16); // 生成0到15的随机整数
            char hexChar = Character.toUpperCase(Character.forDigit(randomInt, 16)); // 将整数转换为十六进制字符并转为大写
            sb.append(hexChar);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Date date = DateUtils.dateTime(SS_MM_HH_DD_HH_YY, "434123181121");
        String s = DateUtils.dateTimeYY(date);
        System.out.println(s);

        String s1 = generateRandomHex(12);
        System.out.println(s1);

    }
}
